//
//  AppDelegate.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/4/18.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit
let SwitchWindowRootViewController = "switchWindowRootViewController"

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

   var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //0、 创建数据库
        FMDBSQLManager.shareSingleManager().opendb("WeiBo.sqlite")
        
        //1、 设置全局的tabbar属性颜色设置
        setUpApprence()
        // 2、注册一个通知，成为监听对象
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(AppDelegate.SwitchDefaultRootVC(_:)), name: SwitchWindowRootViewController, object: nil)
        
     window = UIWindow(frame: UIScreen.mainScreen().bounds)
        //3、 设置一个默认的根视图控制器
     window?.rootViewController = WelcomeViewController(nibName: "WelcomeViewController", bundle: nil)
        //4、 选择真正的根视图控制器
      defaultRootViewController()
        
        window?.makeKeyAndVisible()
     return true
    }

    // 通知调用的方法
    func SwitchDefaultRootVC(notifi : NSNotification) {
     //   print(notifi)
        
        if notifi.object as! Bool {
            window?.rootViewController = MainTabbarController()
        }
        else {
          assert(window != nil, "window不存在")
            window?.rootViewController = WelcomeViewController(nibName: "WelcomeViewController", bundle: nil)
        }
    }

    // 设置全局nav和 tabbar的颜色属性
    func  setUpApprence() {
       UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
    deinit {// 销毁时
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: - 选择默认的根视图控制器
    func defaultRootViewController() {
        if UserAccount.isLogin() {
            window?.rootViewController = fd_checkVersionUpdate() ? NewfeatureCollectionViewController() :  WelcomeViewController(nibName: "WelcomeViewController", bundle: nil)
        }
        else {
            window?.rootViewController = fd_checkVersionUpdate() ? NewfeatureCollectionViewController() : MainTabbarController()
        }
    }
    
    
    //MARK: - 检测版本更新
    func fd_checkVersionUpdate() ->Bool {
        
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
         let lastVersion = NSUserDefaults().objectForKey("CFBundleShortVersionString") as? String ?? ""
        
        if currentVersion.compare(lastVersion) == NSComparisonResult.OrderedDescending {
            // 符合降序
            NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "CFBundleShortVersionString")
            return true
        }
        return false
    }
}

